package top.canyue.word_range_service.flitter;

import top.canyue.word_range.pojo.dto.LoginUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import top.canyue.word_range.utils.JwtUtil;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT验证拦截器
 * @author canyue
 * @version 1.0 2024/06/24
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private ValueOperations<String, LoginUser> valueOperations;
    private final JwtUtil jwtUtil = new JwtUtil();

    // Redis数据前缀
    @Value("${work-range.redis.key-prefix}")
    private String redisKeyPrefix;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("JWT");
        if (!StringUtils.hasText(token)) {             //未认证
            filterChain.doFilter(request, response);   //放行
            return;
        }
        String userId = jwtUtil.getUserIdFromToken(token);
        LoginUser loginUser = valueOperations.get(redisKeyPrefix+ ":" + userId);
        //三个参数的构造，可以标识用户为已认证
        UsernamePasswordAuthenticationToken authenticationToken = null;
        if (loginUser != null) {
            authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        }
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
